/*
 * Copyright (c) 2018-2999 武汉三只猴子科技有限公司 All rights reserved.
 *
 * https://www.3monkeys.shop/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.monkey.shop.api.controller;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.monkey.shop.common.annotation.SysLog;
import com.monkey.shop.common.exception.MonkeyShopBindException;
import com.monkey.shop.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.monkey.shop.bean.app.dto.CategoryDto;
import com.monkey.shop.bean.model.Category;
import com.monkey.shop.service.CategoryService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;

@RestController
@RequestMapping("/category")
@Api(tags = "分类接口")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private MapperFacade mapperFacade;

    /**
     * 分类信息列表接口
     */
    @GetMapping("/categoryInfo")
    @ApiOperation(value = "分类信息列表", notes = "获取所有的产品分类信息，顶级分类的parentId为0,默认为顶级分类")
    @ApiImplicitParam(name = "parentId", value = "分类ID", required = false, dataType = "Long")
    public ResponseEntity<List<CategoryDto>> categoryInfo(@RequestParam(value = "parentId", defaultValue = "0") Long parentId) {
        List<Category> categories = categoryService.listByParentId(parentId);
        List<CategoryDto> categoryDtos = mapperFacade.mapAsList(categories, CategoryDto.class);
        return ResponseEntity.ok(categoryDtos);
    }

    /**
     * 获取分类信息
     */
    @GetMapping("/info/{categoryId}")
    public ResponseEntity<Category> info(@PathVariable("categoryId") Long categoryId){
        Category category = categoryService.getById(categoryId);
        return ResponseEntity.ok(category);
    }



    /**
     * 保存分类
     */
    @SysLog("保存分类")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('prod:category:save')")
    public ResponseEntity<Void> save(@RequestBody Category category){
        category.setShopId(SecurityUtils.getSysUser().getShopId());
        category.setRecTime(new Date());
        Category categoryName = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName())
                .eq(Category::getShopId,category.getShopId()));
        if(categoryName != null){
            throw new MonkeyShopBindException("类目名称已存在！");
        }
        categoryService.saveCategroy(category);
        return ResponseEntity.ok().build();
    }

    /**
     * 更新分类
     */
    @SysLog("更新分类")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('prod:category:update')")
    public ResponseEntity<String> update(@RequestBody Category category){
        category.setShopId(SecurityUtils.getSysUser().getShopId());
        if (Objects.equals(category.getParentId(),category.getCategoryId())) {
            return ResponseEntity.badRequest().body("分类的上级不能是自己本身");
        }
        Category categoryName = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName())
                .eq(Category::getShopId,category.getShopId()).ne(Category::getCategoryId,category.getCategoryId()));
        if(categoryName != null){
            throw new MonkeyShopBindException("类目名称已存在！");
        }
        categoryService.updateCategroy(category);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除分类
     */
    @SysLog("删除分类")
    @DeleteMapping("/{categoryId}")
    @PreAuthorize("@pms.hasPermission('prod:category:delete')")
    public ResponseEntity<String> delete(@PathVariable("categoryId") Long categoryId){
        if (categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getParentId,categoryId)) >0) {
            return ResponseEntity.badRequest().body("请删除子分类，再删除该分类");
        }
        categoryService.deleteCategroy(categoryId);
        return ResponseEntity.ok().build();
    }

    /**
     * 所有的
     */
    @GetMapping("/listCategory")
    public ResponseEntity<List<Category>> listCategory(){

        return ResponseEntity.ok(categoryService.list(new LambdaQueryWrapper<Category>()
                .le(Category::getGrade, 2)
                .eq(Category::getShopId, SecurityUtils.getSysUser().getShopId())
                .orderByAsc(Category::getSeq)));
    }

    /**
     * 所有的产品分类
     */
    @GetMapping("/listProdCategory")
    public ResponseEntity<List<Category>> listProdCategory(){
        List<Category> categories = categoryService.treeSelect(SecurityUtils.getSysUser().getShopId(),2);
        return ResponseEntity.ok(categories);
    }
}
